package com.t360.numberencoding;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * Wrapper around BufferedReader, for reading lines either from stdin, file or socket.
 * It can either read line by line or read all the lines and return them in a list
 * @author fmanganiello
 *
 */
public class LineReader {
	protected List<String> list;
	protected BufferedReader reader;
	
	protected LineReader() {
		this(new ArrayList<String>(), new BufferedReader(new InputStreamReader(System.in)));
	}
	
	protected LineReader(final List<String> list) {
		this(list, new BufferedReader(new InputStreamReader(System.in)));
	}
	
	protected LineReader(final BufferedReader reader) {
		this(new ArrayList<String>(), reader);
	}
	
	protected LineReader(final List<String> list, final BufferedReader reader) {
		this.list = list;
		this.reader = reader;
	}
	
	public static LineReader fromStdin() throws IOException {
		return new LineReader(new BufferedReader(new InputStreamReader(System.in)));
	}
	
	public static LineReader fromFile(final File file) throws IOException {
		return new LineReader(new BufferedReader(new FileReader(file)));
	}
	
	public static LineReader fromSocket(final Socket socket) throws IOException {
		return new LineReader(new BufferedReader(new InputStreamReader(socket.getInputStream())));
	}
	
	public void readAll() throws IOException {
		while (reader.ready()) {
			list.add(reader.readLine());
		}
		
		reader.close();
	}
	
	public List<String> getLines() {
		return list;
	}
	
	public String nextLine() throws IOException {
		if (!reader.ready()) {
			return null;
		}
		
		return reader.readLine();
	}
	
	public boolean ready() throws IOException {
		return reader.ready();
	}
}
